<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>EPUB.js Demo with Reading Progress</title>
    <!-- 添加视口元标签以确保响应式设计在移动设备上正常工作 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!-- 引入 epub.js 依赖 -->
    <script src="{{ url_for('static', filename='js/jquery-3.6.0.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jszip.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/epub.js') }}"></script>
    <!-- 移除 Hammer.js -->
    <!-- <script src="{{ url_for('static', filename='js/hammer.min.js') }}"></script> -->

    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            overflow: hidden; /* 防止在移动端因为固定元素出现双滚动条 */
        }

        /*---------------------------
         * 阅读区域
         *---------------------------*/
        #reader-container {
            height: 100%;
            position: relative;
            overflow: hidden;
        }
        #read {
            width: 100%;
            height: 100%;
            position: relative;
            z-index: 1; /* 确保阅读内容在最上层 */
        }

        /* 左右翻页点击区（用于点击翻页） */
        .page-zone {
            position: absolute;
            top: 0;
            height: 100%;
            cursor: pointer;
            z-index: 5; /* 高于阅读内容区域，以便点击 */
            -webkit-tap-highlight-color: transparent; /* 移除点击高亮 */
            outline: none; /* 移除焦点轮廓 */
            user-select: none; /* 防止文本被选中 */
            touch-action: manipulation; /* 防止默认触摸行为 */
        }
        /* 左侧翻页区 */
        #pageLeft {
            left: 0;
            width: 33.33%;
        }
        /* 中间区域，用于唤起导航栏抽屉 */
        #pageCenter {
            left: 33.33%;
            width: 33.34%;
        }
        /* 右侧翻页区 */
        #pageRight {
            right: 0;
            width: 33.33%;
        }

        /*---------------------------
         * 顶部导航栏（下拉式抽屉）
         *---------------------------*/
        #topNav {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 60px; /* 导航栏高度 */
            background-color: #f8f9fa;
            box-shadow: 0 2px 5px rgba(0,0,0,0.15);
            z-index: 999;
            display: flex;
            align-items: center;
            padding: 0 20px;
            box-sizing: border-box;
            transform: translateY(-100%); /* 初始隐藏在顶部 */
            transition: transform 0.3s ease-in-out;
        }
        #topNav.open {
            transform: translateY(0); /* 显示时下拉到可视区域 */
        }
        /* 返回按钮 */
        #backBtn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 0; /* 去除多余间距 */
            display: flex;
            align-items: center;
        }
        #backBtn img {
            width: 24px;
            height: 24px;
        }

        /*---------------------------
         * 底部导航栏（上拉式抽屉）
         *---------------------------*/
        #controls {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 60px; /* 导航栏高度（PC端） */
            background-color: #f8f9fa;
            box-shadow: 0 -2px 5px rgba(0,0,0,0.15);
            z-index: 999;
            display: flex;
            justify-content: center; /* 水平居中 */
            align-items: center;
            padding: 0 20px;
            transform: translateY(100%); /* 初始隐藏 */
            transition: transform 0.3s ease-in-out;
            box-sizing: border-box; /* 确保padding不影响宽度 */
        }
        /* 打开状态 */
        #controls.open {
            transform: translateY(0);
        }

        /* 中心控制区域 */
        #centerControls {
            display: flex;
            align-items: center;
            flex-wrap: nowrap; /* 禁止换行 */
            gap: 10px; /* 按钮之间的间距 */
            max-width: 1000px; /* 根据需要调整最大宽度 */
            width: 100%;
            justify-content: center; /* 按钮组整体居中 */
        }

        /* 进度条容器 */
        #progressContainer {
            display: flex;
            align-items: center;
            margin: 0 10px;
            flex: 2 1 auto; /* 允许进度条占用更多空间 */
        }
        #progressBar {
            width: 120px;
            margin-right: 5px;
        }
        #progressValue {
            min-width: 50px;
            text-align: left;
            font-size: 12px; /* 调整字体大小 */
        }

        /* 按钮通用样式 */
        .btn {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 8px 12px;
            margin: 0 4px;
            border: none; /* 移除边框 */
            background: none; /* 移除背景色 */
            cursor: pointer;
            font-size: 14px;
            -webkit-tap-highlight-color: transparent; /* 移除点击高亮 */
            outline: none; /* 移除焦点轮廓 */
            user-select: none; /* 防止文本被选中 */
            touch-action: manipulation; /* 防止默认触摸行为 */
            flex: 1 1 auto; /* 允许按钮自适应 */
            max-width: 80px; /* 限制按钮最大宽度 */
            white-space: nowrap; /* 防止按钮文本换行 */
        }
        .btn:focus {
            outline: none; /* 移除焦点轮廓 */
        }

        /* 全屏按钮样式 */
        #fullscreenBtn {
            margin-right: 10px;
            max-width: 100px; /* 增加按钮宽度限制 */
        }

        /*---------------------------
         * 目录 - 右侧抽屉
         *---------------------------*/
        #tocDrawer {
            position: fixed;
            right: 0;
            top: 0;
            width: 250px;
            height: 100vh;
            background-color: #ffffff;
            box-shadow: -2px 0 5px rgba(0,0,0,0.2);
            transform: translateX(100%);
            transition: transform 0.3s ease-in-out;
            overflow-y: auto;
            z-index: 10000; /* 提高 z-index 以确保在导航栏之上 */
            padding: 20px;
            -webkit-tap-highlight-color: transparent; /* 移除点击高亮 */
            box-sizing: border-box;
        }
        #tocDrawer.open { transform: translateX(0); }
        #tocDrawer h3 { margin-top: 0; }
        #tocDrawer ul {
            list-style-type: none;
            padding: 0;
        }
        #tocDrawer li {
            margin: 8px 0;
            cursor: pointer;
            color: #000; /* 将文本颜色改为黑色，移除蓝色 */
            -webkit-tap-highlight-color: transparent; /* 移除点击高亮 */
            outline: none; /* 移除焦点轮廓 */
            user-select: none; /* 防止文本被选中 */
            touch-action: manipulation; /* 防止默认触摸行为 */
        }
        #tocDrawer li:hover { 
            text-decoration: none; /* 移除下划线 */
        }
        #tocDrawer li:focus {
            outline: none; /* 移除焦点轮廓 */
        }

        /*---------------------------
         * 设置 - 底部上拉抽屉
         *---------------------------*/
        #settingsDrawer {
            position: fixed;
            left: 0;
            width: 100%;
            bottom: 0px; /* 紧贴导航栏顶部 */
            max-height: 0; /* 初始收起 */
            background-color: #fff;
            box-shadow: 0 -2px 6px rgba(0,0,0,0.2);
            overflow: hidden;
            transition: max-height 0.3s ease-in-out;
            z-index: 10000; /* 提高 z-index 以确保在导航栏之上 */
            -webkit-tap-highlight-color: transparent; /* 移除点击高亮 */
            box-sizing: border-box;
        }
        #settingsDrawer.open {
            /* 示例高度，可根据实际内容自适应 */
            max-height: 300px;
        }
        #settingsPanelContent {
            padding: 15px;
        }
        #settingsPanelContent h4 {
            margin-top: 0;
        }
        .settings-row {
            margin-bottom: 10px;
        }

        /*---------------------------
         * 按钮内图标样式
         *---------------------------*/
        .btn img {
            width: 24px; /* 根据需要调整图标大小 */
            height: 24px;
            vertical-align: middle;
        }

        /* 隐藏按钮中的文字，仅显示图标 */
        .btn span {
            display: none; /* 隐藏文字 */
        }

        /*---------------------------
         * 移动端自适应
         *---------------------------*/
        @media (max-width: 768px) {
            /* 增加导航栏高度 */
            #controls { 
                height: 100px; /* 增加导航栏高度 */
                padding: 10px 20px; /* 调整内边距 */
            }

            /* 导航按钮更大 */
            .btn {
                padding: 10px 8px; /* 调整填充 */
                font-size: 16px; /* 调整字体大小 */
                flex: 1 1 auto; /* 允许按钮自适应 */
                max-width: 80px; /* 限制按钮最大宽度 */
            }

            /* 进度条宽度略减 */
            #progressBar {
                width: 100px;
            }

            /* 目录字体更大 */
            #tocDrawer li {
                font-size: 20px;
                color: #000; /* 确保在移动模式下文字颜色为黑色 */
            }

            /* 设置抽屉更高一些 */
            #settingsDrawer.open {
                max-height: 360px;
            }

            /* 调整目录抽屉宽度为屏幕的一半 */
            #tocDrawer {
                width: 50%; /* 设置为屏幕宽度的50% */
            }

            /* 隐藏上一页和下一页按钮 */
            #prevPageBtn,
            #nextPageBtn {
                display: none;
            }

            /* 调整剩余按钮的间距 */
            #centerControls {
                gap: 8px; /* 减小按钮间距以适应增大的按钮 */
                flex-wrap: nowrap; /* 确保不换行 */
                justify-content: space-between; /* 使按钮均匀分布 */
            }

            /* 调整进度条容器的间距 */
            #progressContainer {
                margin: 0 8px;
                flex: 2 1 auto; /* 允许进度条占用更多空间 */
            }

            /* 确保目录和设置按钮也不换行 */
            #tocBtn,
            #settingsBtn,
            #fullscreenBtn {
                white-space: nowrap; /* 防止按钮文本换行 */
                flex: 1 1 auto; /* 允许按钮自适应 */
                max-width: 80px; /* 限制按钮最大宽度 */
            }

            /* 确保进度值不占用过多空间 */
            #progressValue {
                font-size: 12px; /* 调整字体大小 */
                max-width: 60px; /* 限制最大宽度 */
            }

            /* 顶部导航在小屏也相应增高 */
            #topNav {
                height: 80px;
            }
        }
    </style>
</head>
<body>

<!-- 顶部导航栏（下拉式抽屉） -->
<div id="topNav">
    <button id="backBtn" aria-label="返回">
        <img src="{{ url_for('static', filename='icons/返回箭头_详情页.svg') }}" alt="返回">
    </button>
</div>

<!-- 阅读区域 -->
<div id="reader-container">
    <div id="read"></div>
    <!-- 左右翻页点击区（点击翻页时启用） -->
    <div id="pageLeft" class="page-zone"></div>
    <div id="pageCenter" class="page-zone"></div>
    <div id="pageRight" class="page-zone"></div>
</div>

<!-- 右侧抽屉式目录 -->
<div id="tocDrawer">
    <h3>目录</h3>
    <ul id="tocList"></ul>
</div>

<!-- 底部导航栏（上拉式抽屉） -->
<div id="controls">
    <!-- 中心控制区域 -->
    <div id="centerControls">
        <!-- 全屏按钮 -->
        <button class="btn" id="fullscreenBtn">
            <img src="{{ url_for('static', filename='icons/24gl-fullScreenEnter2.svg') }}" alt="全屏">
            <span>全屏</span>
        </button>
        
        <!-- 进度条 -->
        <div id="progressContainer">
            <input type="range" id="progressBar" min="0" max="100" value="0">
            <span id="progressValue">0.00%</span>
        </div>
        
        <!-- 其他按钮 -->
        <button class="btn" id="tocBtn">
            <img src="{{ url_for('static', filename='icons/目录.svg') }}" alt="目录">
            <span>目录</span>
        </button>
        <button class="btn" id="prevPageBtn">
            <img src="{{ url_for('static', filename='icons/308上一页、后退、返回.svg') }}" alt="上一页">
            <span>上一页</span>
        </button>
        <button class="btn" id="nextPageBtn">
            <img src="{{ url_for('static', filename='icons/309下一页、前进、查看更多.svg') }}" alt="下一页">
            <span>下一页</span>
        </button>
        <button class="btn" id="settingsBtn">
            <img src="{{ url_for('static', filename='icons/设置.svg') }}" alt="设置">
            <span>设置</span>
        </button>
    </div>
</div>

<!-- 底部上拉式抽屉（设置面板） -->
<div id="settingsDrawer">
    <div id="settingsPanelContent">
        <h4>阅读设置</h4>
        <div class="settings-row">
            <label for="backcolor">背景色:</label>
            <input type="color" id="backcolor" value="#ffffff">
        </div>
        <div class="settings-row">
            <label for="textcolor">字体颜色:</label>
            <input type="color" id="textcolor" value="#000000">
        </div>
        <div class="settings-row">
            <label for="fontSizeRange">字体大小:</label>
            <input type="range" id="fontSizeRange" min="12" max="36" step="1" value="16">
            <span id="fontSizeValue">16px</span>
        </div>
        <div class="settings-row">
            <label for="letterSpacingRange">字间距:</label>
            <input type="range" id="letterSpacingRange" min="0" max="10" step="0.5" value="0">
            <span id="letterSpacingValue">0px</span>
        </div>
        <div class="settings-row">
            <label for="lineHeightRange">行高:</label>
            <input type="range" id="lineHeightRange" min="0.1" max="3" step="0.1" value="1.5">
            <span id="lineHeightValue">1.5</span>
        </div>
        <!-- 翻页模式选择 -->
        <div class="settings-row">
            <label for="flipModeSelect">翻页模式:</label>
            <select id="flipModeSelect">
                <option value="both" selected>点击 + 滑动</option>
                <option value="click">仅点击</option>
                <option value="swipe">仅滑动</option>
            </select>
        </div>
    </div>
</div>

<script>
    var rendition;
    var book;
    var locations;
    var isTocOpen = false;      // 目录抽屉是否打开
    var isSettingsOpen = false; // 设置抽屉是否打开
    var isControlsOpen = false; // 导航栏是否打开（同时控制顶部和底部）
    // 翻页模式：默认 both （点击+滑动）
    var currentFlipMode = "both";

    var GET_PROGRESS_API = "/api/reading_progress/"; 
    var POST_PROGRESS_API = "/api/reading_progress";
    // 新增：阅读偏好接口
    var GET_PREFERENCE_API = "/api/user_preference";
    var POST_PREFERENCE_API = "/api/user_preference";

    document.addEventListener('DOMContentLoaded', async () => {
        // 0. 给返回按钮添加“返回上一页”逻辑
        var backBtn = document.getElementById("backBtn");
        backBtn.addEventListener("click", function(event) {
            event.stopPropagation();
            // 执行返回上一页
            history.back();
        });

        // 1. 获取电子书路径并初始化
        var urlParams = new URLSearchParams(window.location.search);
        var bookId   = "{{ book_id }}";    
        var bookPath = "{{ book_path }}";
        if (!bookPath || !bookId) {
            alert("缺少必要的 bookPath 或 book_id！");
            return;
        }

        // 2. 加载并渲染电子书
        var book = ePub(bookPath);
        rendition = book.renderTo("read", {
            width: "100%",
            height: "100%"
        });

        // 3. 获取后端保存的进度，如果有的话就跳转到对应位置
        try {
            let response = await fetch(GET_PROGRESS_API + bookId);
            let result = await response.json();
            if (result.success && result.data && result.data.cfi) {
                // 如果后端返回了阅读进度
                let cfi = result.data.cfi;
                // 跳转到保存的 cfi
                rendition.display(cfi);
            } else {
                // 如果没保存过进度，则从头开始
                rendition.display();
            }
        } catch (e) {
            console.warn("获取阅读进度失败：", e);
            // 如果出错，也可以默认为从头开始
            rendition.display();
        }

        // 4. 生成 locations，用于进度计算
        //    注意：如果书比较大，这里可能比较耗时
        book.ready
            .then(function() {
                applyTheme();
                return book.locations.generate(1600); // 1600 = 估算每章节字符数(可调整)
            })
            .then(function() {
                locations = book.locations;
            });

        // 5. 加载用户阅读偏好（记忆阅读配置），并应用
        await loadUserPreference();

        // 监听翻页完成（或位置变动）事件，把最新的进度发给后端
        rendition.on("relocated", function(location){
            updateProgressUI(location);
            saveReadingProgress(location, bookId);
        });

        // =============== 目录抽屉 ===============
        var tocBtn = document.getElementById("tocBtn");
        var tocDrawer = document.getElementById("tocDrawer");
        tocBtn.addEventListener("click", function(event) {
            event.stopPropagation(); // 防止触发阅读区域的点击事件
            isTocOpen = !isTocOpen;
            tocDrawer.classList.toggle("open", isTocOpen);
            if (isTocOpen) {
                // 打开目录时，关闭其他抽屉
                closeAllDrawersExcept('toc');
            }
        });
        book.loaded.navigation.then(function(toc) {
            var tocList = document.getElementById("tocList");
            tocList.innerHTML = "";
            toc.forEach(function(chapter) {
                var li = document.createElement("li");
                li.textContent = chapter.label;
                li.addEventListener("click", function(event) {
                    event.stopPropagation(); // 防止触发阅读区域的点击事件
                    rendition.display(chapter.href);
                    // 关闭目录
                    isTocOpen = false;
                    tocDrawer.classList.remove("open");
                });
                tocList.appendChild(li);
            });
        });

        // =============== 翻页按钮 ===============
        document.getElementById("prevPageBtn").addEventListener("click", function(event) {
            event.stopPropagation(); // 防止触发阅读区域的点击事件
            rendition.prev();
        });
        document.getElementById("nextPageBtn").addEventListener("click", function(event) {
            event.stopPropagation(); // 防止触发阅读区域的点击事件
            rendition.next();
        });

        // =============== 进度条 & 百分比 ===============
        var progressBar = document.getElementById("progressBar");
        var progressValue = document.getElementById("progressValue");

        function updateProgressUI(location) {
            if (!locations || !location || !location.start) return;
            var progress = locations.percentageFromCfi(location.start.cfi);
            if (progress !== undefined) {
                var percent = (progress * 100).toFixed(2);
                progressBar.value = percent;
                progressValue.textContent = percent + "%";
            }
        }

        progressBar.addEventListener("change", function(event) {
            event.stopPropagation(); // 防止触发阅读区域的点击事件
            if (!locations) return;
            var percent = parseFloat(progressBar.value) / 100;
            var cfi = locations.cfiFromPercentage(percent);
            rendition.display(cfi);
        });

        // =============== 设置抽屉（上拉） ===============
        var settingsBtn = document.getElementById("settingsBtn");
        var settingsDrawer = document.getElementById("settingsDrawer");
        settingsBtn.addEventListener("click", function(event) {
            event.stopPropagation(); // 防止触发阅读区域的点击事件
            isSettingsOpen = !isSettingsOpen;
            settingsDrawer.classList.toggle("open", isSettingsOpen);
            if (isSettingsOpen) {
                // 打开设置时，关闭其他抽屉
                closeAllDrawersExcept('settings');
            }
        });

        // =============== 设置选项 ===============
        var backcolorInput     = document.getElementById("backcolor");
        var textcolorInput     = document.getElementById("textcolor");
        var fontSizeRange      = document.getElementById("fontSizeRange");
        var letterSpacingRange = document.getElementById("letterSpacingRange");
        var lineHeightRange    = document.getElementById("lineHeightRange");

        var fontSizeValue      = document.getElementById("fontSizeValue");
        var letterSpacingValue = document.getElementById("letterSpacingValue");
        var lineHeightValue    = document.getElementById("lineHeightValue");

        // 当用户在设置面板改变任何选项时，立即应用并保存到后端
        backcolorInput.addEventListener("change",  handleSettingsChange);
        textcolorInput.addEventListener("change",  handleSettingsChange);
        fontSizeRange.addEventListener("input",    handleSettingsChange);
        letterSpacingRange.addEventListener("input", handleSettingsChange);
        lineHeightRange.addEventListener("input",  handleSettingsChange);

        function handleSettingsChange() {
            // 更新显示
            fontSizeValue.textContent = fontSizeRange.value + "px";
            letterSpacingValue.textContent = letterSpacingRange.value + "px";
            lineHeightValue.textContent = lineHeightRange.value;
            // 应用到阅读器
            applyTheme();
            // 保存到后端
            updateUserPreference();
        }

        /**
         * 应用主题样式
         */
        function applyTheme() {
            var themeStyle = {
                "body": {
                    "background": backcolorInput.value,
                    "color": textcolorInput.value,
                    "font-size": fontSizeRange.value + "px",
                    "letter-spacing": letterSpacingRange.value + "px"
                },
                "p, li, h1, h2, h3, h4, h5, h6, span, div": {
                    "line-height": lineHeightRange.value + " !important"
                }
            };
            rendition.themes.register("customTheme", themeStyle);
            rendition.themes.select("customTheme");
        }

        // =============== 全屏按钮 ===============
        var fullscreenBtn = document.getElementById("fullscreenBtn");
        fullscreenBtn.addEventListener("click", function(event) {
            event.stopPropagation(); // 防止触发阅读区域的点击事件
            toggleFullscreen();
        });

        function toggleFullscreen() {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen().catch(err => {
                    alert(`全屏模式开启失败: ${err.message} (${err.name})`);
                });
                // 替换为退出全屏的图标
                fullscreenBtn.querySelector('img').src = "{{ url_for('static', filename='icons/24gl-fullScreenExit2.svg') }}";
                fullscreenBtn.querySelector('img').alt = "退出全屏";
            } else {
                document.exitFullscreen();
                // 恢复全屏图标
                fullscreenBtn.querySelector('img').src = "{{ url_for('static', filename='icons/24gl-fullScreenEnter2.svg') }}";
                fullscreenBtn.querySelector('img').alt = "全屏";
            }
        }

        // 监听全屏变化以同步按钮图标
        document.addEventListener('fullscreenchange', () => {
            if (!document.fullscreenElement) {
                fullscreenBtn.querySelector('img').src = "{{ url_for('static', filename='icons/24gl-fullScreenEnter2.svg') }}";
                fullscreenBtn.querySelector('img').alt = "全屏";
            } else {
                fullscreenBtn.querySelector('img').src = "{{ url_for('static', filename='icons/24gl-fullScreenExit2.svg') }}";
                fullscreenBtn.querySelector('img').alt = "退出全屏";
            }
        });

        // =============== 翻页模式选择 ===============
        var flipModeSelect = document.getElementById("flipModeSelect");
        flipModeSelect.addEventListener("change", function(event) {
            event.stopPropagation(); // 防止触发阅读区域的点击事件
            setFlipMode(this.value);
            // 同步到后端
            updateUserPreference();
        });

        // 初始化翻页模式（此处可能在加载用户偏好后会被覆盖）
        var pageLeftZone = document.getElementById("pageLeft");
        var pageRightZone = document.getElementById("pageRight");
        var pageCenterZone = document.getElementById("pageCenter");

        // 全局变量用于触摸事件
        var touchStartX = 0;
        var touchStartY = 0;
        var touchEndX = 0;
        var touchEndY = 0;
        var swipeThreshold = 50; // 滑动最小距离

        // 默认翻页模式：both
        setFlipMode("both");

        function setFlipMode(mode) {
            currentFlipMode = mode;
            // 1) 点击翻页
            if (currentFlipMode === "click" || currentFlipMode === "both") {
                pageLeftZone.style.display = "block";
                pageRightZone.style.display = "block";
            } else {
                pageLeftZone.style.display = "none";
                pageRightZone.style.display = "none";
            }
            // 2) 滑动翻页
            // 已在下方实现
        }

        // 点击翻页事件
        pageLeftZone.addEventListener("click", function(event) {
            if (currentFlipMode === "click" || currentFlipMode === "both") {
                rendition.prev();
            }
            event.stopPropagation(); // 防止触发阅读区域的点击事件
        });
        pageRightZone.addEventListener("click", function(event) {
            if (currentFlipMode === "click" || currentFlipMode === "both") {
                rendition.next();
            }
            event.stopPropagation(); // 防止触发阅读区域的点击事件
        });

        // 中间区域点击事件，用于唤起/收回导航栏抽屉（此处同步控制顶部和底部）
        pageCenterZone.addEventListener("click", function(event) {
            event.stopPropagation(); 
            isControlsOpen = !isControlsOpen;
            // 同步打开或收起顶部导航和底部导航
            document.getElementById("controls").classList.toggle("open", isControlsOpen);
            document.getElementById("topNav").classList.toggle("open", isControlsOpen);

            if (isControlsOpen) {
                // 打开导航时，关闭其他抽屉
                closeAllDrawersExcept('controls');
            } else {
                // 收回导航栏时，确保其他抽屉也关闭
                isTocOpen = false;
                tocDrawer.classList.remove("open");
                isSettingsOpen = false;
                settingsDrawer.classList.remove("open");
            }
        });

        // =============== 滑动翻页实现 ===============
        var readerContainer = document.getElementById("reader-container");

        readerContainer.addEventListener("touchstart", function(event) {
            if (currentFlipMode === "swipe" || currentFlipMode === "both") {
                touchStartX = event.changedTouches[0].screenX;
                touchStartY = event.changedTouches[0].screenY;
            }
        }, false);

        readerContainer.addEventListener("touchend", function(event) {
            if (currentFlipMode === "swipe" || currentFlipMode === "both") {
                touchEndX = event.changedTouches[0].screenX;
                touchEndY = event.changedTouches[0].screenY;
                handleGesture();
            }
        }, false);

        function handleGesture() {
            var deltaX = touchEndX - touchStartX;
            var deltaY = touchEndY - touchStartY;

            // 确保滑动方向主要是水平
            if (Math.abs(deltaX) > Math.abs(deltaY)) {
                if (Math.abs(deltaX) > swipeThreshold) {
                    if (deltaX < 0) {
                        // 向左滑动
                        rendition.next();
                    } else {
                        // 向右滑动
                        rendition.prev();
                    }
                }
            }
        }

        // =============== 自动单双页模式 ===============
        function setDisplayMode() {
            if (window.innerWidth >= window.innerHeight) {
                rendition.spread("always");
            } else {
                rendition.spread("none");
            }
        }
        setDisplayMode();
        window.addEventListener("resize", setDisplayMode);

        // =============== 点击其他区域关闭所有抽屉 ===============
        document.addEventListener("click", function(event) {
            var controls = document.getElementById("controls");
            var toc = document.getElementById("tocDrawer");
            var settings = document.getElementById("settingsDrawer");
            var topNav = document.getElementById("topNav");

            // 如果点击的目标不在任何抽屉内，也不在控制按钮内，则关闭所有抽屉
            if (
                !controls.contains(event.target) && 
                !toc.contains(event.target) && 
                !settings.contains(event.target) &&
                !topNav.contains(event.target) &&
                !event.target.closest('.btn')
            ) {
                if (isControlsOpen) {
                    isControlsOpen = false;
                    controls.classList.remove("open");
                    topNav.classList.remove("open");
                }
                if (isTocOpen) {
                    isTocOpen = false;
                    tocDrawer.classList.remove("open");
                }
                if (isSettingsOpen) {
                    isSettingsOpen = false;
                    settingsDrawer.classList.remove("open");
                }
            }
        });

        /**
         * 关闭所有抽屉，除了指定的抽屉
         * @param {string} except - 不关闭的抽屉，值可以是 'controls', 'toc', 'settings'
         */
        function closeAllDrawersExcept(except) {
            // 如果 except 不是 'controls'，就要把顶部/底部都收起来
            if (except !== 'controls' && isControlsOpen) {
                isControlsOpen = false;
                document.getElementById("controls").classList.remove("open");
                document.getElementById("topNav").classList.remove("open");
            }
            if (except !== 'toc' && isTocOpen) {
                isTocOpen = false;
                document.getElementById("tocDrawer").classList.remove("open");
            }
            if (except !== 'settings' && isSettingsOpen) {
                isSettingsOpen = false;
                document.getElementById("settingsDrawer").classList.remove("open");
            }
        }
    });

    /**
     * 将阅读进度保存到后端
     * @param {object} location - ePub.js返回的定位对象，包含start.cfi等
     * @param {string|number} bookId - 书籍ID（数据库中的主键）
     */
    async function saveReadingProgress(location, bookId) {
        if (!location || !location.start) return;
        var cfi = location.start.cfi;

        // 如果你想存百分比：
        var percent = 0;
        if (locations) {
            var progress = locations.percentageFromCfi(cfi);
            percent = progress ? (progress * 100) : 0;
        }

        try {
            await fetch(POST_PROGRESS_API, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    book_id: bookId,
                    cfi: cfi,
                    progress_percentage: percent
                })
            });
        } catch (err) {
            console.error("保存阅读进度失败：", err);
        }
    }

    /**
     * 加载用户偏好，并应用到设置面板和阅读器
     */
    async function loadUserPreference() {
        try {
            let res = await fetch("/api/user_preference");
            let result = await res.json();
            if (result.success) {
                let data = result.data;
                // 获取页面上对应的控件
                let backcolorInput     = document.getElementById("backcolor");
                let textcolorInput     = document.getElementById("textcolor");
                let fontSizeRange      = document.getElementById("fontSizeRange");
                let letterSpacingRange = document.getElementById("letterSpacingRange");
                let lineHeightRange    = document.getElementById("lineHeightRange");
                let fontSizeValue      = document.getElementById("fontSizeValue");
                let letterSpacingValue = document.getElementById("letterSpacingValue");
                let lineHeightValue    = document.getElementById("lineHeightValue");
                let flipModeSelect     = document.getElementById("flipModeSelect");

                // 设置控件的当前值
                backcolorInput.value        = data.background_color;
                textcolorInput.value        = data.text_color;
                fontSizeRange.value         = data.font_size;
                letterSpacingRange.value    = data.letter_spacing;
                lineHeightRange.value       = data.line_height;
                flipModeSelect.value        = data.flip_mode;

                // 同步文本显示
                fontSizeValue.textContent      = data.font_size + "px";
                letterSpacingValue.textContent = data.letter_spacing + "px";
                lineHeightValue.textContent    = data.line_height;

                // 应用到阅读器
                applyTheme();
                setFlipMode(data.flip_mode);
            }
        } catch (err) {
            console.error("加载用户偏好失败: ", err);
        }
    }

    /**
     * 将最新的用户偏好传到后端
     */
    async function updateUserPreference() {
        try {
            // 获取当前界面选项
            let backcolorInput     = document.getElementById("backcolor");
            let textcolorInput     = document.getElementById("textcolor");
            let fontSizeRange      = document.getElementById("fontSizeRange");
            let letterSpacingRange = document.getElementById("letterSpacingRange");
            let lineHeightRange    = document.getElementById("lineHeightRange");
            let flipModeSelect     = document.getElementById("flipModeSelect");

            let newPref = {
                background_color: backcolorInput.value,
                text_color: textcolorInput.value,
                font_size: parseInt(fontSizeRange.value),
                letter_spacing: parseFloat(letterSpacingRange.value),
                line_height: parseFloat(lineHeightRange.value),
                flip_mode: flipModeSelect.value
            };

            let res = await fetch(POST_PREFERENCE_API, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(newPref)
            });
            let result = await res.json();
            if (!result.success) {
                console.warn("更新偏好失败：", result.message);
            }
        } catch (err) {
            console.error("更新阅读偏好时出错: ", err);
        }
    }
</script>
</body>
</html>
